package com.yixia.common.handle.mybatisPlus;

import com.yixia.common.utils.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 依梦
 * @Date 2023/9/1
 */
public class StringListTypeHandle extends BaseTypeHandler<List<String>> {

    // 将对象集合转换成数据库对象，
    // List<Long> ---> 12121,212121,12121,
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        StringBuilder sb = new StringBuilder();
        // 集合不为空
        if(parameter != null && parameter.size() > 0){
            for (String aLong : parameter) {
                sb.append(aLong).append(",");
            }
        }
        ps.setString(i, sb.toString());
    }

    // 将数据库转换成对象集合
    // 12121,212121,12121 ---> List<Long>
    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String values = resultSet.getString(s);
        return this.parseList(values);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String values = resultSet.getString(i);
        return this.parseList(values);
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String values = callableStatement.getString(i);
        return this.parseList(values);
    }

    // 将值变成集合
    private List<String> parseList(String value){
        List<String> list = new ArrayList<>();
        if(value != null){
            String[] split = value.split(",");
            for (String s : split) {
                if(StringUtils.isNotEmpty(s)) {
                    list.add(s);
                }
            }
        }
        return list;
    }
}
